import axios from 'axios';
import { saveAs } from 'file-saver';
import { ElNotification, ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';
import { tansParams } from '@/utils/base';
import errorCode from '@/utils/errorCode';
import cache from '@/plugins/cache';
import { sm4 } from 'sm-crypto-v2';
import CryptoJS from 'crypto-js';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 30000,
});

service.interceptors.request.use(
  async (config) => {
    config.data = config?.data ?? {};

    if (config.encryptReq || config.decryptRes) {
      if (!config.retry) {
        config.originalData = config.data;
      }

      if (config.encryptReq) {
        config.data = encryptRequestSolo(
          config.originalData,
          config.encryptType,
          config.encryptKey,
        );
      }
    }

    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken();
    }

    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }

    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
    if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
      const requestObj = {
        url: config.url,
        data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime(),
      };
      const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
      const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
      if (requestSize >= limitSize) {
        console.warn(
          `[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。',
        );
        return config;
      }
      const sessionObj = cache.session.getJSON('sessionObj');
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        cache.session.setJSON('sessionObj', requestObj);
      } else {
        const s_url = sessionObj.url; // 请求地址
        const s_data = sessionObj.data; // 请求数据
        const s_time = sessionObj.time; // 请求时间
        const interval = 500; // 间隔时间(ms)，小于此时间视为重复提交
        if (
          s_data === requestObj.data &&
          requestObj.time - s_time < interval &&
          s_url === requestObj.url
        ) {
          const message = '数据正在处理，请勿重复提交';
          return Promise.reject(new Error(message));
        } else {
          cache.session.setJSON('sessionObj', requestObj);
        }
      }
    }

    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

service.interceptors.response.use(
  (res) => {
    // 对响应解密
    if (res.config.decryptRes && res.data && typeof res.data === 'string') {
      res.data = decryptResponseSolo(res.data, res.config.encryptType, res.config.encryptKey);
    }

    // 二进制数据则直接下载
    if (res.request.responseType === 'blob') {
      const filename = res.config?.filename ?? '未命名文件';
      const blob = new Blob([res.data]);
      saveAs(blob, filename);
      return;
    }

    const code = res?.data?.code ?? 200;
    const msg = res?.data?.msg ?? errorCode?.[code] ?? errorCode['default'];

    if (code !== 200) {
      ElNotification.error({ title: msg });
      return Promise.reject(res.data);
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error) => {
    ElMessage({
      message: error?.message ?? errorCode['default'],
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  },
);

export function encryptRequestSolo(data, encryptType, encryptKey) {
  let dataStr = typeof data === 'string' ? data : JSON.stringify(data);
  if ('SM4' === encryptType) {
    // 加密，默认输出 16 进制字符串，默认使用 pkcs#7 填充（传 pkcs#5 也会走 pkcs#7 填充）
    data = sm4.encrypt(dataStr, encryptKey);
  } else if ('AES' === encryptType) {
    const key = CryptoJS.enc.Hex.parse(encryptKey);
    data = CryptoJS.AES.encrypt(dataStr, key, {
      format: CryptoJS.format.Hex,
      mode: CryptoJS.mode.ECB,
    }).ciphertext.toString(CryptoJS.enc.Hex);
  } else {
    throw '加密失败，不支持的对称加密算法类型：' + encryptType;
  }
  return data;
}

export function decryptResponseSolo(data, encryptType, encryptKey) {
  if (typeof data === 'string') {
    if ('SM4' === encryptType) {
      // 加密，默认输出 16 进制字符串，默认使用 pkcs#7 填充（传 pkcs#5 也会走 pkcs#7 填充）
      let decrypted = sm4.decrypt(data, encryptKey);
      return JSON.parse(decrypted.toString());
    } else if ('AES' === encryptType) {
      const key = CryptoJS.enc.Hex.parse(encryptKey);
      let decrypted = CryptoJS.AES.decrypt(data.toString(), key, {
        format: CryptoJS.format.Hex,
        mode: CryptoJS.mode.ECB,
      });
      return JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
    } else {
      throw '加密失败，不支持的对称加密算法类型：' + encryptType;
    }
  }
}

export default service;
